package com.caiheng.api.service.attendance.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.caiheng.api.dao.attendance.AttendanceGroupMapper;
import com.caiheng.api.dao.attendance.AttendanceMapper;
import com.caiheng.api.entity.attendance.Attendance;
import com.caiheng.api.entity.attendance.AttendanceGroup;
import com.caiheng.api.entity.attendance.AttendanceGroupUser;
import com.caiheng.api.entity.estate.Estate;
import com.caiheng.api.entity.sys.SysUser;
import com.caiheng.api.entity.wxuser.User;
import com.caiheng.api.exception.TransactionalException;
import com.caiheng.api.service.attendance.AttendanceService;
import com.caiheng.api.service.base.impl.BaseServiceImpl;
import com.caiheng.api.service.estate.EstateService;
import com.caiheng.api.service.sys.SysUserService;
import com.caiheng.api.util.DateUtil;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.Date;
import java.util.Map;

/**
 * 考勤Service业务层处理
 *
 * @author ruoyi
 * @date 2022-09-19
 */
@Service
public class AttendanceServiceImpl extends BaseServiceImpl<AttendanceMapper, Attendance> implements AttendanceService {

    @Resource
    private AttendanceMapper attendanceMapper;
    @Resource
    private AttendanceGroupMapper attendanceGroupMapper;
    @Resource
    private SysUserService sysUserService;
    @Resource
    private EstateService estateService;


    @Override
    @Transactional
    public int addLeave(User user, SysUser sysUser,String leaveType, String leaveBeginDate, String leaveBeginTime, String leaveEndDate, String leaveEndTime, String remark, double leaveTime, String imgs) {
        int ret = 0;
        try{
            Attendance attendance = new Attendance();
            attendance.setPropertyId(sysUser.getPropertyId());
            attendance.setEstateId(sysUser.getEstateId());
            if(sysUser.getEstateId() !=null && sysUser.getEstateId() > 0){
                Estate estate = estateService.findById(sysUser.getEstateId());
                if(estate!=null){
                    attendance.setEstateName(estate.getEstateName());
                }
            }

            attendance.setDeptId(sysUser.getDeptId());
            attendance.setUserId(user.getId());
            attendance.setCreateTime(new Date());
            attendance.setSysUserId(sysUser.getUserId());
            attendance.setSysUserName(sysUser.getNickName());
            attendance.setState(4);//请假
            attendance.setHolidayState(4);
            attendance.setAmOrPm(0);
            attendance.setRemark(remark);
            attendance.setIsOut(0);
            attendance.setLeaveType(leaveType);
            attendance.setLeaveBeginDate(DateUtil.formatDate(leaveBeginDate));
            attendance.setLeaveEndDate(DateUtil.formatDate(leaveEndDate));
            attendance.setLeaveBeginTime(leaveBeginTime);
            attendance.setLeaveEndTime(leaveEndTime);
            attendance.setLeaveTime(leaveTime);

            double times = leaveTime / 0.5;
            attendance.setTotalSignCount((int)times);
            attendance.setDutyGroupId(sysUser.getDutyGroupId());

            ret = attendanceMapper.insert(attendance);
            if(ret <= 0){
                throw new TransactionalException("attendanceMapper updateById error");
            }


        }catch (Exception e){
            e.printStackTrace();
        }
        return ret;
    }


    /**
     * 检查是否已打卡
     *
     * @param user
     * @param type   0-上班打卡 1-下班打卡
     * @return
     */
    @Override
    public boolean isCheckAttendance(User user, AttendanceGroupUser groupUser, int type) {
        AttendanceGroup attendanceGroup = null;
        if (groupUser.getGroupId() == null || groupUser.getGroupId() == 0) {
            QueryWrapper<AttendanceGroup> qw = new QueryWrapper<>();
            qw.eq("is_default", 1);
            if(groupUser.getUserType() == 0){
                qw.eq("property_id", groupUser.getPropertyId());
            }else{
                qw.eq("estate_id", groupUser.getEstateId());
            }
            attendanceGroup = attendanceGroupMapper.selectOne(qw);
        } else {
            attendanceGroup = attendanceGroupMapper.selectById(groupUser.getGroupId());
        }
        if (attendanceGroup != null) {
            Date amBeginDutyTime = DateUtil.fomatTime(DateUtil.getDay() + " " + attendanceGroup.getAmBeginDutyTime() + ":00");
            Date amEndDutyTime = DateUtil.fomatTime(DateUtil.getDay() + " " + attendanceGroup.getAmEndDutyTime() + ":00");
            Date pmBeginDutyTime = DateUtil.fomatTime(DateUtil.getDay() + " " + attendanceGroup.getPmBeginDutyTime() + ":00");
            Date pmEndDutyTime = DateUtil.fomatTime(DateUtil.getDay() + " " + attendanceGroup.getPmEndDutyTime() + ":00");
            Date zeroTime = DateUtil.fomatTime(DateUtil.getDay() + " 00:00:00");
            Date lastTime = DateUtil.fomatTime(DateUtil.getDay() + " 23:59:59");

            int amEndDutyHour = attendanceGroup.getAmEndDutyHour();
            Date amEndDutyTimeAfter = DateUtil.getAfterSecondsByOld(amEndDutyTime,amEndDutyHour * 60 * 60);
            Date pmBeginDutyTimeBefore =  DateUtil.getAfterSecondsByOld(pmBeginDutyTime,-amEndDutyHour * 60 * 60);


            QueryWrapper<Attendance> qw = new QueryWrapper<>();
            qw.eq("user_id", user.getId());
            qw.ne("state", 4);//非请假
            if (type == 0) {//上午 上班打卡
                // 0: 00 ~ 8:30(11:30)
                qw.eq("am_or_pm", type);
                qw.between("create_time", DateUtil.getTime(zeroTime), DateUtil.getTime(amEndDutyTime));
            } else if (type == 1) {//中午下班打卡
                // 11:30 ~ 12:30
                qw.eq("am_or_pm", type);
                qw.between("create_time", DateUtil.getTime(amEndDutyTime),  DateUtil.getTime(pmBeginDutyTime));
            } else if (type == 2) {//下午上班打卡
                qw.eq("am_or_pm", type);
                qw.between("create_time", DateUtil.getTime(pmBeginDutyTimeBefore), DateUtil.getTime(pmEndDutyTime));
            } else if (type == 3) {//下午下班打卡
                qw.eq("am_or_pm", type);
                qw.between("create_time", DateUtil.getTime(pmEndDutyTime), DateUtil.getTime(lastTime));
            }
            qw.last("limit 1");
            Attendance attendance = attendanceMapper.selectOne(qw);
            return attendance != null;
        }
        return false;
    }

    @Override
    @Transactional
    public int addCheck(Attendance attendance) {
        int ret = 0;
        try{
            ret = attendanceMapper.insert(attendance);
            if(ret <= 0){
                throw new TransactionalException("attendanceMapper updateById error");
            }
            ret = attendance.getId();
        }catch (Exception e){
            e.printStackTrace();
        }
        return ret;
    }

    @Override
    public Double getLeaveDaysByUserId(Map<String, Object> map) {
        return attendanceMapper.getLeaveDaysByUserId(map);
    }

    @Override
    public Attendance getTodayAttendance(AttendanceGroup attendanceGroup, User user, int type) {
        Attendance attendance = null;
        if (attendanceGroup != null) {
            Date amBeginDutyTime = DateUtil.fomatTime(DateUtil.getDay() + " " + attendanceGroup.getAmBeginDutyTime() + ":00");
            Date amEndDutyTime = DateUtil.fomatTime(DateUtil.getDay() + " " + attendanceGroup.getAmEndDutyTime() + ":00");
            Date pmBeginDutyTime = DateUtil.fomatTime(DateUtil.getDay() + " " + attendanceGroup.getPmBeginDutyTime() + ":00");
            Date pmEndDutyTime = DateUtil.fomatTime(DateUtil.getDay() + " " + attendanceGroup.getPmEndDutyTime() + ":00");
            Date zeroTime = DateUtil.fomatTime(DateUtil.getDay() + " 00:00:00");
            Date lastTime = DateUtil.fomatTime(DateUtil.getDay() + " 23:59:59");

            int amEndDutyHour = attendanceGroup.getAmEndDutyHour();
            Date amEndDutyTimeAfter = DateUtil.getAfterSecondsByOld(amEndDutyTime,amEndDutyHour * 60 * 60);
            Date pmBeginDutyTimeBefore =  DateUtil.getAfterSecondsByOld(pmBeginDutyTime,-amEndDutyHour * 60 * 60);

            QueryWrapper<Attendance> qw = new QueryWrapper<>();
            qw.eq("user_id", user.getId());
            qw.ne("state", 4);//非请假
            if (type == 0) {//上午 上班打卡
                // 0: 00 ~ 8:30(11:30)
                qw.eq("am_or_pm", type);
                qw.between("create_time", DateUtil.getTime(zeroTime), DateUtil.getTime(amEndDutyTime));
            } else if (type == 1) {//中午下班打卡
                // 11:30 ~ 12:30
                qw.eq("am_or_pm", type);
                qw.between("create_time", DateUtil.getTime(amEndDutyTime),  DateUtil.getTime(pmBeginDutyTime));
            } else if (type == 2) {//下午上班打卡
                qw.eq("am_or_pm", type);
                qw.between("create_time", DateUtil.getTime(pmBeginDutyTimeBefore), DateUtil.getTime(pmEndDutyTime));
            } else if (type == 3) {//下午下班打卡
                qw.eq("am_or_pm", type);
                qw.between("create_time", DateUtil.getTime(pmEndDutyTime), DateUtil.getTime(lastTime));
            }
            qw.last("limit 1");
            attendance = attendanceMapper.selectOne(qw);
        }
        return attendance;
    }

}
